import axios from 'axios'
import qs from 'qs'
import Session from '@/utils/store'
import { getQueryParams } from '@/utils/utils.js'
import mpAdapter from 'axios-miniprogram-adapter'
import small from '@/smallapp/small'
// import { isWeixinCient } from '@/utils/validate'
  axios.defaults.adapter = mpAdapter
  axios.defaults.withCredentials = true



// create an axios instance
const service = axios.create({
  baseURL: small.globalData.appApiUrl, // api的base_url
  method: 'get',
  // timeout: 30000, // request timeout
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    Cookie: window.document.$$cookie ?  window.document.$$cookie : '', // 后端不能直接设置小程序的请求头cookie 需要自己设置
    // Cookie: 'qb_log_uuid=9e66e5c4-ce39-a88b-8174-0599255abcaa; qb_log_ftime=1592371913783; Lng=120.2985; Lat=30.41875; district=%25E4%25BD%2599%25E6%259D%25AD%25E5%258C%25BA%2C%25E6%259D%25AD%25E5%25B7%259E%25E5%25B8%2582%2C%25E6%25B5%2599%25E6%25B1%259F%25E7%259C%2581%2C%25E4%25B8%25AD%25E5%259B%25BD; loc_name=%25E4%25BD%2599%25E6%259D%25AD%25E5%258C%25BA; user_auth=think%3A%7B%22uid%22%3A%2213487%22%2C%22last_time%22%3A%221594611911%22%2C%22shop_id%22%3A%226%22%2C%22status%22%3A%221%22%7D; user_auth_sign=8f4b9b910abbd18b64c3a7af27ece372f0fdbe1a; real_pid=13487; shop_id=6; PHPSESSID=13f75u7uba7hjqnt65v2g9si7d; is_not_first=0; qb_log_ls=1594869031240; pid=13487; lastLoginData=16.7.2020; VisitShopStr=shop%3A0; global_wechat_isInWexin=false; global_openUrlInApp=true; WFX_OPEN_IN_APP_FIRST=1594869049936; qb_log_depth=6; item_list_page6=1; detail_ajax=1594869063%407d9a9bec65cbca9bd029efc052418aa8c4218b193d7eed8c07aef45b55bd4346'
  }
})


// request interceptor
service.interceptors.request.use((config) => {
  // Do something before request is sent
  if (typeof config.params !== 'object') {
    config.params = {
      // t: new Date().getTime()
    }
  }
  config.headers['X-REQUESTED-WITH'] = 'XMLHttpRequest'
  config.headers['X-MAPP-ID'] = small.globalData.wxAppid
  config.headers['X-MAPP-TOKEN'] = small.wxCache('global_login_info') ? small.wxCache('global_login_info').token : '0'
  config.headers['X-MAPP-ORIGIN'] = small.globalData.origin
  config.headers['X-MAPP-SMALLVERSION'] = small.globalData.appVersion
  config.params.sid = small.globalData.shopId
  config.params.pid = small.wxCache('global_login_info') ? small.wxCache('global_login_info').uid : '0'
  // 开店礼包后端无法区分小程序页面，所以需要过滤的页面添加storeGift=1
  if (window.location.pathname == '/item-bargain-detail' || window.location.pathname == '/gift-detail' || window.location.pathname == '/item-collocate-detail' || window.location.pathname == '/shop-car' || window.location.pathname == '/item-group' || window.location.pathname == '/storeGift' || window.location.pathname == '/buySuccess' || window.location.pathname == '/item-detail' || window.location.pathname == '/order-lists' || window.location.pathname == '/buy' || window.location.pathname == '/order-detail') {
    config.params.storeGift = 1
  }
  // 微分销限流 新增appid(店铺id)和userid（会员当前登录的id）
  config.headers['appid'] = config.params.sid || '0'
  config.headers['userid'] = config.params.pid || '0'

  if (config.type !== 'file') {
    config.data = qs.stringify(config.data)
  }
  return config
}, (error) => {
  // Do something with request error
  // console.log(error) // for debug
  Promise.reject(error)
})

// respone interceptor
service.interceptors.response.use(
  (response) => {
    // // console.log('response:', response)
    const setCookie = response.headers['Set-Cookie']
    window.document.$$setCookie ? window.document.$$setCookie(setCookie) : '' // 小程序请求头自己设置set-cookie
    let res
    if (response.config.url == '/PassportApi/loginByMini') {
      res = response
    } else {
      res = response.data
    }
    if (res.errorCode == 'FROZEN') {
      wx.redirectTo({
        url: `/activity/pages/errorPage/index?type=jump&targeturl=${encodeURIComponent('/errorPage?msg='+res.msg)}`
      })
    }
    // TODO 直接返回结果 如果后台返回了跳转链接 在页面里面单独处理
    return res
  },
  (error) => {
    // console.log(`err${error}`)// for debug
    const errData = error.response.data
    if (error.response.status == 510 && window.location.pathname != '/sysBusyPrompt') { // 510代表店铺被限流
      wx.redirectTo({
        url: `/activity/pages/sysBusyPrompt/index?type=jump&targeturl=${encodeURIComponent('/sysBusyPrompt')}&sid=${errData.real_shop_id}&close_num=${errData.sid_close_num}`
      })
    }
    return Promise.reject(error)
  })

export default service
